// pages/main/available house/available.js
const url = "https://zbnczy.com"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    houseArray: [],//在页面展示的五个数据
    defaultArray: [],//每次筛选后的所有数据
    twonIndex: 0,
    twons: ["所有", "海流图乡", "庙东营"],
    villageIndex: 0,
    villages: ["所有"],
    areaIndex: 0,
    areaMin: [0,0,41,51,71],
    areaMax: [65535,40,50,70,65535],
    areas: ["所有", "0~40", "41~50", "51~70", "70以上"],
    propertyIndex: 0,
    propertys: ["个人"],
    tranYearIndex: 0,
    tranMin: [0,0,41,51,71],
    tranMax: [65535,40,50,70,65535],
    tranYears: ["所有", "0~20", "20~40", "40~60", "60及以上"],
    sortIndex: 0,
    defaultSort: ["恢复默认排序", "按面积升序", "按面积降序", "按流转年限升序", "按流转年限降序", "按发布时间排序"],
    sortWay: ["cover_area", "transtime"],
    searchContext: "",
    maxPages: 1,
    pagesNum: 1,
    tyindex: 1,
    frontPage: false,
    lastPage: true
  },
  /**
   * 对wx.request封装，默认get方法
   */
  request(url, method = "GET") {
    return new Promise(
      (resolve, reject) => {
        wx.request({
          url,
          success: (res) => {
            resolve(res);
          },
          fail: (e) => {
            console.log(e);
          }
        })
      }
    )
  },
  JumpTo(houseinfo) {
    wx.navigateTo({
      url: `/pages/main/availablehouse/info/info`,
      success: function (res) {
        let houseInfo = houseinfo.currentTarget.dataset.houseinfo
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('tranHouseInfo', {
          houseInfo
        })
      }
    })
  },
    /**
   * 生命周期函数--监听页面加载
   */
  onLoad:async function (options) {
    this.setData({
      pagesNum: 1,
      tyindex: 1,
      lastPage: true,
      frontPage: false,
    })
    //初始化获得数据
  const res = await this.request(`${url}/house/selectbyproperty/个人`)
  this.setData({defaultArray: res.data.sort((a, b) => a.defaultSort - b.defaultSort)})
  const {defaultArray} = this.data
  this.setData({
      houseArray: defaultArray.slice(0, 5),
      maxPages: parseInt(defaultArray.length / 5) + Boolean(defaultArray.length % 5)
    })

  //请求乡镇栏数据
    const res1 = await this.request(`${url}/house/visitTown`)
    this.setData({twons: ["所有", ...res1.data]})
},
  /**
   * 动态获取搜索框的值
   * @param {event} e 
   */
  getContext(e) {
    this.setData({
      searchContext: e.detail.value
    })
  },
  /**
   * 搜索的点击事件
   */
  searchHouse() {
    console.log(this.data.searchContext);
    this.handleConfirmInput()
  },
  handleConfirmInput:async function() {
    this.setData({twonIndex:0,villageIndex:0,areaIndex:0, tranYearIndex:0,sortIndex:0})
    const res = await this.request(`${url}/house/selectbyproperty/个人`)
    let newArray = res.data.filter(item => item.title.includes(this.data.searchContext))
    this.setData({
      pagesNum: 1,
      tyindex: 1,
      lastPage: true,
      frontPage: false,
    })
    this.setData({
        defaultArray: newArray,
        houseArray: newArray.slice(0, 5),
        maxPages: parseInt(newArray.length / 5) + Boolean(newArray.length % 5)
    })
  },

  //对于每次筛选条件的改变，或者onload(),返回初始状态，或者setHouseArray(),页码重新开始，defaultArray改变
  setHouseArray(res) {
    //页码重新开始
    this.setData({pagesNum: 1,tyindex: 1,lastPage: true,frontPage: false,})
    this.setData({ defaultArray: res})
    const {defaultArray} = this.data
    this.setData({
        houseArray: defaultArray.slice(0, 5),
        pagesNum: 1,
        maxPages: parseInt(defaultArray.length / 5) + Boolean(defaultArray.length % 5)
      })
  },
  //获取乡镇下所有房屋数据
  getDataByTown: async function (twon) {
    const res = await this.request(`${url}/house/select/${twon}/1`)
    //产权不用筛选，固定个人
    const data = res.data.filter((item => item.property == "个人"))
    return data;
  },
  //获得所选乡镇的村
  getVillageByTown: async function (twon) {
    const res = await this.request(`${url}/house/select/${twon}`)
    return res.data;
  },
  //获得乡镇下具体村的数据
  getDataByTownVill: async function(twon,village) {
   const res = await this.request(`${url}/house/select/${twon}/${village}`)
   //同样筛选个人
   const data = res.data.filter((item => item.property == "个人"))
   return data
  },
  //根据面积范围筛选
  getDataByArea: async function(areaMin,areaMax){
    const res = await this.request(`${url}/house/select/cover_area/${areaMin}/${areaMax}`)
    const data = res.data.filter((item => item.property == "个人"))
    return data;
  },
  //根据产权筛选
  getDataByProperty: async function (property){
    const res = await this.request(`${url}/house/selectbyproperty/${property}`)
    return  res.data 
  },
  //根据流转年限筛选
  getDataByTranstime :async function (tranMin,tranMax){
    const res = await  this.request(`${url}/house/select/transtime/${tranMin}/${tranMax}`)
    const data = res.data.filter((item => item.property == "个人"))
    return data
  },
  //排序
  getDataBySort : async function (sortBy,howSort,min,max){
   const res = await this.request(`${url}/house/select/${sortBy}/${howSort}/${min}/${max}`)
   const data = res.data.filter((item => item.property == "个人"))
   return data
  },
  // 处理筛选，0~5，乡镇 -> 排序，
  bindPickerChange: async function (e) {
    /**
     *  乡镇和村是相互联系的，选乡镇时，请求其所有村名
     *  面积筛选，现在是没和乡镇村关联，选择面积，会重置其他项所有，这里也可以关联乡镇村,           
     *  产权筛选，这里固定为个人     
     *  流转年限，同样与其他没关联，选择后会重置其他项为所有,由于现在流转年限均为null,无法查询， 
     *  排序，后端API, `${url}/house/select/${sortWay[sortWayIndex]}/${howSort}/${min}/${max}`
     *        sortWay{"cover_area"：根据面积, "transtime"：根据流转年限}
     *        howSort = 1  是升序     soM = 2 是降序
     *        min      max     是面积或者流转年限的范围
     * 排序是和面积，流转年限相关的，在基础上排序;和村镇无关，选择后重置村镇
     */
    switch (e.currentTarget.dataset.num) {
      case 0: {
        this.setData({ twonIndex: parseInt(e.detail.value) })
        const { twonIndex, twons } = this.data
        if (twonIndex == 0) {
          this.setData({ villages: ["所有"] })
          //返回初始状态
          this.onLoad()
        } else {
          //获取所选乡镇所有数据
          const data = await this.getDataByTown(twons[twonIndex]);
          //获取村
          const vill = await this.getVillageByTown(twons[twonIndex]);
          this.setData({ villages: ["所有", ...vill] })
          this.setHouseArray(data)
        }
        break;
      }
      case 1: {
        this.setData({villageIndex: parseInt(e.detail.value)})
        const {twonIndex,twons,villageIndex,villages} = this.data
        //村子筛选为所有
        if (villages[villageIndex] == "所有") {
          if (this.data.twonIndex == 0) this.onLoad()
          else {
            const data = await this.getDataByTown(twons[twonIndex]);
            this.setHouseArray(data)
          }
        }
        //不为所有
        const res =await this.getDataByTownVill(twons[twonIndex],villages[villageIndex])
        this.setHouseArray(res)
        break;
      }
      case 2: {
        this.setData({areaIndex: parseInt(e.detail.value)})
        this.setData({twonIndex:0,villageIndex:0,tranYearIndex:0,sortIndex:0})
        const {areaIndex} = this.data
        this.setData({twonIndex:0,villageIndex:0})
        const {areaMin,areaMax} = this.data
        const res = await this.getDataByArea(areaMin[areaIndex],areaMax[areaIndex])
        this.setHouseArray(res)
        break;
      }
      case 3: {
        this.setData({propertyIndex: parseInt(e.detail.value)})
        const {propertyIndex,propertys} = this.data
        this.setData({twonIndex: 0,villageIndex: 0})
        if (propertyIndex == 0) {
          this.setData({twonIndex: 0,villageIndex: 0})
          this.onLoad()
        } else {//产权固定为个人，这里也可以不处理
          const res = await this.getDataByProperty(propertys[propertyIndex])
          this.setHouseArray(res)
      }
      break;
    }
      case 4: {
        this.setData({tranYearIndex: parseInt(e.detail.value)})
        this.setData({twonIndex:0,villageIndex:0,areaIndex:0,sortIndex:0})
        const {tranYearIndex} = this.data
          const {tranMax,tranMin} = this.data
          const res = await this.getDataByTranstime(tranMin[tranYearIndex],tranMax[tranYearIndex])
          this.setHouseArray(res)
        break;
      }
      case 5: {
        this.setData({twonIndex:0,villageIndex:0})
        this.setData({sortIndex: parseInt(e.detail.value)})
        const {sortIndex,sortWay} = this.data
        const {areaIndex,areaMax,areaMin} = this.data
        const {tranYearIndex,tranMin,tranMax} = this.data
        //默认排序，
        if (sortIndex == 0) this.onLoad()
        //其他
        else {
          let sortWayIndex, howSort,min,max;
          //选择根据面积或者年限,并设置min,max
          if (sortIndex == 1 || sortIndex == 2) {
            sortWayIndex = 0;
            min = areaMin[areaIndex]
            max = areaMax[areaIndex]
          }
          else if (sortIndex == 3 || sortIndex == 4) {
            sortWayIndex = 1;
            min = tranMin[tranYearIndex]
            max = tranMax[tranYearIndex]
          }
          //选择升序降序
          if (sortIndex == 1 || sortIndex == 3) howSort = 1;
          else if (sortIndex == 2 || sortIndex == 4) howSort = 2;
          const res = await this.getDataBySort(sortWay[sortWayIndex],howSort,min,max)
          this.setHouseArray(res)
        }
        break;
      }
      default:
        break;
    }
  },


  /**
   * 分页处理
   * @tyindex  tyindex表示每五个数的第一个，1，6，11...
   * @pagesNum 点击前选中的数字
   * @maxPages 数据总数
   * @frontPage boolean 
   * @lastPage  boolean
   *  前箭头显示条件：frontPage == true && maxPages > 5
   *  后箭头显示条件：lastPage == true && maxPages > 5
   */
<<<<<<< HEAD
  onShareAppMessage: function () {

  },
  //翻页函数
=======
>>>>>>> 918965ce7ed10cd94cd73c0ebeb2facb2d66bac6
  pagesFn: function (e) {
    /*
      下方分页统一使用pagesFn()，通过参数区分
      data-type 为参数，前箭头：data-type="previous_page",
                        后箭头：data-type="next_page",
                        首页：data-type="start"
                        尾页：data-type="end"
                        索引：data-type=(index)%5
      data-number      点击的值 data-number = tyindex + index ，
                       其中index仅当做0-4使用，
                      
    */
    let type = e.currentTarget.dataset.type;
    let number = e.currentTarget.dataset.number;
    if (typeof type == "string") {
      //点击上一页
      if (type == "previous_page") {
        // //如果当前为1，点击上一页，无效；可以不判断，
        //    原因：当展示到最后五个数字，并不会显示下一页按钮
        // if (this.data.pagesNum - 1 < 1) {
        //   return false
        // }
        //如果当前为五个数字最左侧，点击上一个
        if ((this.data.pagesNum - 1) % 5 == 0) {
          //如果点击后，回到1-5，设置前箭头不显示，后箭头显示
          if ((this.data.pagesNum - 6) < 1) {
            this.setData({
              lastPage: true,
              frontPage: false,
            })
          }
          //否则，后箭头显示,设置tyindex
          this.setData({
            lastPage: true,
            tyindex: this.data.pagesNum - 5,
            pagesNum: this.data.pagesNum - 1,
          })
        }
        //如果不是最左侧，仅设置当前页数减一
        else {
          this.setData({
            pagesNum: this.data.pagesNum - 1,
          })
        }
      }
      //点击下一页
      else if (type == "next_page") {
        ////如果当前为最大页数，点击下一页，无效；可以不判断，同上
        // if (this.data.pagesNum + 1 > this.data.maxPages) {
        //   return false;
        // }
        //如果当前为五个数字最右侧，点击下一个
        if (this.data.pagesNum % 5 == 0) {
          //
          if ((this.data.pagesNum + 5) >= 5) {
            this.setData({
              lastPage: true,
              frontPage: true,
            })
          }
          if ((this.data.pagesNum + 5) >= this.data.maxPages) {
            this.setData({
              lastPage: false
            })
          }
          this.setData({
            tyindex: this.data.pagesNum + 1,
            pagesNum: this.data.pagesNum + 1,
          })
        }
        //如果不是五个数字最右侧，点击下一个，
        else {
          this.setData({
            pagesNum: this.data.pagesNum + 1,
          })
        }
      } else if (type == "start") { //第一页
        this.setData({
          pagesNum: 1,
          tyindex: 1,
          lastPage: true,
          frontPage: false,
        })
      } else { //最后一页
        if ((this.data.maxPages % 5) == 0) {
          this.setData({
            pagesNum: this.data.maxPages,
            tyindex: this.data.maxPages - 4,
            lastPage: false,
            frontPage: true,
          })
        }

        else {
          this.setData({
            pagesNum: this.data.maxPages,
            tyindex: this.data.maxPages + 1 - (this.data.maxPages % 5),
            lastPage: false,
            frontPage: true,
          })
        }
      }
    }
    //如果是数字
    else {
      this.setData({
        pagesNum: number
      })
    }
    console.log(this.data.pagesNum)
    //经过上面的处理获得最终的页码 pagesNum
    const {
      defaultArray,
      pagesNum
    } = this.data
    let pre = (pagesNum - 1) * 5
    let next = pre + 5
    this.setData({
      houseArray: defaultArray.slice(pre, next)
    })
    console.log(this.data.houseArray);
  },
})